package org.lecric.wind44.server.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.lecric.wind44.client.model.Post;
import org.lecric.wind44.client.service.MobileService;
import org.lecric.wind44.server.model.DBPost;
import org.lecric.wind44.server.model.DBUtil;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class MobileServiceImpl extends RemoteServiceServlet implements MobileService
{
	@Override
	public void clearPosts()
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			pm.deletePersistentAll(getDBPosts(pm));
		}
		finally
		{
			pm.close();
		}
	}

	@Override
	public List<Post> getPosts()
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Post> posts=new ArrayList<Post>();
		try
		{
			for(DBPost dbPost: getDBPosts(pm))
			{
				Post post = DBUtil.db2pojo(dbPost);
				posts.add(post);
			}
		}
		finally
		{
			pm.close();
		}
		return posts;
	}

	@Override
	public Post post(Post post)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			Post result = DBUtil.db2pojo(pm.makePersistent(DBUtil.pojo2db(post)));
			return result;
		}
		finally
		{
			pm.close();
		}
	}

	private List<DBPost> getDBPosts(PersistenceManager pm) {
		Query query = pm.newQuery(DBPost.class);
		try
		{
			return (List<DBPost>) query.execute();
		}
		finally
		{
			query.closeAll();
		}
	}
}
